import { UploadOutlined } from '@ant-design/icons';
import { Button, Upload } from 'antd';
import { RcFile } from 'antd/lib/upload';
import { memo, useImperativeHandle, useRef, useState } from 'react';
import { useUpload } from '../../utils/upload';
import { ILawsRef } from '../../types';
import type { UploadFile } from 'antd';


export interface IUploadData {
  onRef: React.MutableRefObject<ILawsRef | undefined>;
}
const UploadFile = ({ onRef }: IUploadData) => {
  const uploadFile = useRef<string>()

  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const upload = useUpload();
  const beforeUpload = async (file: RcFile) => {
    setFileList([file]);
    const formData = new FormData();
    formData.append("file", file);
    const result = await upload('https://yjws.jxhzszkj.com/firecheck/base/uploadFileToLocal', {
      data: {
        file
      },
    });
    uploadFile.current = result
    return false;
  };
  const onRemove = () => {
    setFileList([]);
  };


  /**
    * 向外暴露文件的地址
    */
  useImperativeHandle(onRef, () => ({
    getData: () => {
      console.log(uploadFile.current);
      return uploadFile.current
    },
    rest: () => {
      setFileList([])
    },
    fill: (val: string) => {
      setFileList([{
        uid: '1',
        name: val
      }])
    }
  }));

  return (
    <Upload accept={'.pdf, .docx'} onRemove={onRemove} fileList={fileList} maxCount={1} beforeUpload={beforeUpload}>
      <Button icon={<UploadOutlined />}>
        开始上传
      </Button>
    </Upload>
  );
};


export default memo(UploadFile)